<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/myblogs/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/myblogs/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/myblogs/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/myblogs/images/logo.svg" color="#222">

<link rel="stylesheet" href="/myblogs/css/main.css">


<link rel="stylesheet" href="/myblogs/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/myblogs/lib/pace/pace-theme-minimal.min.css">
  <script src="/myblogs/lib/pace/pace.min.js"></script>


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('http://hackmgod.gitee.io').hostname,
    root: '/myblogs/',
    scheme: 'Gemini',
    version: '7.7.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="原型模式（原型设计模式）详解">
<meta property="og:type" content="article">
<meta property="og:title" content="【13】原型模式（原型设计模式）详解">
<meta property="og:url" content="http://hackmgod.gitee.io/2020/01/17/%E3%80%9013%E3%80%91%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%8E%9F%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="H.m博客">
<meta property="og:description" content="原型模式（原型设计模式）详解">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101Fa22.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101K4L9.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114102002601.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101SUJ.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114102049214.gif">
<meta property="og:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q11410212a20.gif">
<meta property="article:published_time" content="2020-01-17T05:59:17.000Z">
<meta property="article:modified_time" content="2020-01-17T10:07:20.857Z">
<meta property="article:author" content="H.m">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101Fa22.gif">

<link rel="canonical" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9013%E3%80%91%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%8E%9F%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>【13】原型模式（原型设计模式）详解 | H.m博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/myblogs/atom.xml" title="H.m博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/myblogs/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">H.m博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">www.hackm.cn</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/myblogs/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/myblogs/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/myblogs/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://hackmgod.gitee.io/2020/01/17/%E3%80%9013%E3%80%91%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%8E%9F%E5%9E%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
      <meta itemprop="name" content="H.m">
      <meta itemprop="description" content="欢迎您的到来！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="H.m博客">
    </span>
      <header class="post-header">
		
        <h1 class="post-title" itemprop="name headline">
          【13】原型模式（原型设计模式）详解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-01-17 13:59:17 / 修改时间：18:07:20" itemprop="dateCreated datePublished" datetime="2020-01-17T13:59:17+08:00">2020-01-17</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/myblogs/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">设计模式</span>
                  </a>
                </span>
            </span>

          
            <div class="post-description">原型模式（原型设计模式）详解</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="【13】原型模式（原型设计模式）详解"><a href="#【13】原型模式（原型设计模式）详解" class="headerlink" title="【13】原型模式（原型设计模式）详解"></a>【13】原型模式（原型设计模式）详解</h2><p>在有些系统中，存在大量相同或相似对象的创建问题，如果用传统的构造函数来创建对象，会比较复杂且耗时耗资源，用原型模式生成对象就很高效，就像孙悟空拔下猴毛轻轻一吹就变出很多孙悟空一样简单。</p>
<h2 id="原型模式的定义与特点"><a href="#原型模式的定义与特点" class="headerlink" title="原型模式的定义与特点"></a>原型模式的定义与特点</h2><p>原型（Prototype）模式的定义如下：用一个已经创建的实例作为原型，通过复制该原型对象来创建一个和原型相同或相似的新对象。在这里，原型实例指定了要创建的对象的种类。用这种方式创建对象非常高效，根本无须知道对象创建的细节。例如，Windows 操作系统的安装通常较耗时，如果复制就快了很多。在生活中复制的例子非常多，这里不一一列举了。</p>
<h2 id="原型模式的结构与实现"><a href="#原型模式的结构与实现" class="headerlink" title="原型模式的结构与实现"></a>原型模式的结构与实现</h2><p>由于 Java 提供了对象的 clone() 方法，所以用 Java 实现原型模式很简单。</p>
<h3 id="1-模式的结构"><a href="#1-模式的结构" class="headerlink" title="1. 模式的结构"></a>1. 模式的结构</h3><p>原型模式包含以下主要角色。<br>抽象原型类：规定了具体原型对象必须实现的接口。<br>具体原型类：实现抽象原型类的 clone() 方法，它是可被复制的对象。<br>访问类：使用具体原型类中的 clone() 方法来复制新的对象。</p>
<p>其结构图如图 1 所示。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101Fa22.gif" alt="原型模式的结构图"><br>图1 原型模式的结构图</p>
<h3 id="2-模式的实现"><a href="#2-模式的实现" class="headerlink" title="2. 模式的实现"></a>2. 模式的实现</h3><p>原型模式的克隆分为浅克隆和深克隆，Java 中的 Object 类提供了浅克隆的 clone() 方法，具体原型类只要实现 Cloneable 接口就可实现对象的浅克隆，这里的 Cloneable 接口就是抽象原型类。其代码如下：<br>//具体原型类</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">class Realizetype implements Cloneable</span><br><span class="line">&#123;</span><br><span class="line">    Realizetype()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;具体原型创建成功！&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    public Object clone() throws CloneNotSupportedException</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;具体原型复制成功！&quot;);</span><br><span class="line">        return (Realizetype)super.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;原型模式的测试类</span><br><span class="line">public class PrototypeTest</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)throws CloneNotSupportedException</span><br><span class="line">    &#123;</span><br><span class="line">        Realizetype obj1&#x3D;new Realizetype();</span><br><span class="line">        Realizetype obj2&#x3D;(Realizetype)obj1.clone();</span><br><span class="line">        System.out.println(&quot;obj1&#x3D;&#x3D;obj2?&quot;+(obj1&#x3D;&#x3D;obj2));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序的运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">具体原型创建成功！</span><br><span class="line">具体原型复制成功！</span><br><span class="line">obj1&#x3D;&#x3D;obj2?false</span><br></pre></td></tr></table></figure>

<h2 id="原型模式的应用实例"><a href="#原型模式的应用实例" class="headerlink" title="原型模式的应用实例"></a>原型模式的应用实例</h2><p>【例1】用原型模式模拟“孙悟空”复制自己。</p>
<p>分析：孙悟空拔下猴毛轻轻一吹就变出很多孙悟空，这实际上是用到了原型模式。这里的孙悟空类 SunWukong 是具体原型类，而 Java 中的 Cloneable 接口是抽象原型类。</p>
<p>同前面介绍的猪八戒实例一样，由于要显示孙悟空的图像（点击此处下载该程序所要显示的孙悟空的图片），所以将孙悟空类定义成面板 JPanel 的子类，里面包含了标签，用于保存孙悟空的图像。</p>
<p>另外，重写了 Cloneable 接口的 clone() 方法，用于复制新的孙悟空。访问类可以通过调用孙悟空的 clone() 方法复制多个孙悟空，并在框架窗体 JFrame 中显示。图 2 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101K4L9.gif" alt="孙悟空生成器的结构图"><br>图2 孙悟空生成器的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line">import java.awt.*;</span><br><span class="line">import javax.swing.*;</span><br><span class="line">class SunWukong extends JPanel implements Cloneable</span><br><span class="line">&#123;</span><br><span class="line">    private static final long serialVersionUID &#x3D; 5543049531872119328L;</span><br><span class="line">    public SunWukong()</span><br><span class="line">    &#123;</span><br><span class="line">        JLabel l1&#x3D;new JLabel(new ImageIcon(&quot;src&#x2F;Wukong.jpg&quot;));</span><br><span class="line">        this.add(l1);   </span><br><span class="line">    &#125;</span><br><span class="line">    public Object clone()</span><br><span class="line">    &#123;</span><br><span class="line">        SunWukong w&#x3D;null;</span><br><span class="line">        try</span><br><span class="line">        &#123;</span><br><span class="line">            w&#x3D;(SunWukong)super.clone();</span><br><span class="line">        &#125;</span><br><span class="line">        catch(CloneNotSupportedException e)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;拷贝悟空失败!&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        return w;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class ProtoTypeWukong</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        JFrame jf&#x3D;new JFrame(&quot;原型模式测试&quot;);</span><br><span class="line">        jf.setLayout(new GridLayout(1,2));</span><br><span class="line">        Container contentPane&#x3D;jf.getContentPane();</span><br><span class="line">        SunWukong obj1&#x3D;new SunWukong();</span><br><span class="line">        contentPane.add(obj1);       </span><br><span class="line">        SunWukong obj2&#x3D;(SunWukong)obj1.clone();</span><br><span class="line">        contentPane.add(obj2);   </span><br><span class="line">        jf.pack();       </span><br><span class="line">        jf.setVisible(true);</span><br><span class="line">        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序的运行结果如图 3 所示。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q114102002601.gif" alt="孙悟空克隆器的运行结果"><br>图3 孙悟空克隆器的运行结果</p>
<p>用原型模式除了可以生成相同的对象，还可以生成相似的对象，请看以下实例。</p>
<p>【例2】用原型模式生成“三好学生”奖状。</p>
<p>分析：同一学校的“三好学生”奖状除了获奖人姓名不同，其他都相同，属于相似对象的复制，同样可以用原型模式创建，然后再做简单修改就可以了。图 4 所示是三好学生奖状生成器的结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q114101SUJ.gif" alt="奖状生成器的结构图"><br>图4 奖状生成器的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line">public class ProtoTypeCitation</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args) throws CloneNotSupportedException</span><br><span class="line">    &#123;</span><br><span class="line">        citation obj1&#x3D;new citation(&quot;张三&quot;,&quot;同学：在2016学年第一学期中表现优秀，被评为三好学生。&quot;,&quot;韶关学院&quot;);</span><br><span class="line">        obj1.display();</span><br><span class="line">        citation obj2&#x3D;(citation) obj1.clone();</span><br><span class="line">        obj2.setName(&quot;李四&quot;); </span><br><span class="line">        obj2.display();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F;奖状类</span><br><span class="line">class citation implements Cloneable</span><br><span class="line">&#123;</span><br><span class="line">    String name;</span><br><span class="line">    String info;</span><br><span class="line">    String college;</span><br><span class="line">    citation(String name,String info,String college)</span><br><span class="line">    &#123;</span><br><span class="line">        this.name&#x3D;name;</span><br><span class="line">        this.info&#x3D;info;</span><br><span class="line">        this.college&#x3D;college;</span><br><span class="line">        System.out.println(&quot;奖状创建成功！&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">    void setName(String name)</span><br><span class="line">    &#123;</span><br><span class="line">        this.name&#x3D;name;</span><br><span class="line">    &#125;</span><br><span class="line">    String getName()</span><br><span class="line">    &#123;</span><br><span class="line">        return(this.name);</span><br><span class="line">    &#125;</span><br><span class="line">    void display()</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(name+info+college);</span><br><span class="line">    &#125;</span><br><span class="line">    public Object clone() throws CloneNotSupportedException</span><br><span class="line">    &#123;</span><br><span class="line">        System.out.println(&quot;奖状拷贝成功！&quot;);</span><br><span class="line">        return (citation)super.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>程序运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">奖状创建成功！</span><br><span class="line">张三同学：在2016学年第一学期中表现优秀，被评为三好学生。韶关学院</span><br><span class="line">奖状拷贝成功！</span><br><span class="line">李四同学：在2016学年第一学期中表现优秀，被评为三好学生。韶关学院</span><br></pre></td></tr></table></figure>

<h2 id="原型模式的应用场景"><a href="#原型模式的应用场景" class="headerlink" title="原型模式的应用场景"></a>原型模式的应用场景</h2><p>原型模式通常适用于以下场景。</p>
<ul>
<li>对象之间相同或相似，即只是个别的几个属性不同的时候。</li>
<li>对象的创建过程比较麻烦，但复制比较简单的时候。<h2 id="原型模式的扩展"><a href="#原型模式的扩展" class="headerlink" title="原型模式的扩展"></a>原型模式的扩展</h2>原型模式可扩展为带原型管理器的原型模式，它在原型模式的基础上增加了一个原型管理器 PrototypeManager 类。该类用 HashMap 保存多个复制的原型，Client 类可以通过管理器的 get(String id) 方法从中获取复制的原型。其结构图如图 5 所示。</li>
</ul>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q114102049214.gif" alt="带原型管理器的原型模式的结构图"><br>图5 带原型管理器的原型模式的结构图</p>
<p>【例3】用带原型管理器的原型模式来生成包含“圆”和“正方形”等图形的原型，并计算其面积。分析：本实例中由于存在不同的图形类，例如，“圆”和“正方形”，它们计算面积的方法不一样，所以需要用一个原型管理器来管理它们，图 6 所示是其结构图。</p>
<p><img src="http://c.biancheng.net/uploads/allimg/181114/3-1Q11410212a20.gif" alt="图形生成器的结构图"><br>图6 图形生成器的结构图</p>
<p>程序代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line">import java.util.*;</span><br><span class="line">interface Shape extends Cloneable</span><br><span class="line">&#123;</span><br><span class="line">    public Object clone();    &#x2F;&#x2F;拷贝</span><br><span class="line">    public void countArea();    &#x2F;&#x2F;计算面积</span><br><span class="line">&#125;</span><br><span class="line">class Circle implements Shape</span><br><span class="line">&#123;</span><br><span class="line">    public Object clone()</span><br><span class="line">    &#123;</span><br><span class="line">        Circle w&#x3D;null;</span><br><span class="line">        try</span><br><span class="line">        &#123;</span><br><span class="line">            w&#x3D;(Circle)super.clone();</span><br><span class="line">        &#125;</span><br><span class="line">        catch(CloneNotSupportedException e)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;拷贝圆失败!&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        return w;</span><br><span class="line">    &#125;</span><br><span class="line">    public void countArea()</span><br><span class="line">    &#123;</span><br><span class="line">        int r&#x3D;0;</span><br><span class="line">        System.out.print(&quot;这是一个圆，请输入圆的半径：&quot;);</span><br><span class="line">        Scanner input&#x3D;new Scanner(System.in);</span><br><span class="line">        r&#x3D;input.nextInt();</span><br><span class="line">        System.out.println(&quot;该圆的面积&#x3D;&quot;+3.1415*r*r+&quot;\n&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">class Square implements Shape</span><br><span class="line">&#123;</span><br><span class="line">    public Object clone()</span><br><span class="line">    &#123;</span><br><span class="line">        Square b&#x3D;null;</span><br><span class="line">        try</span><br><span class="line">        &#123;</span><br><span class="line">            b&#x3D;(Square)super.clone();</span><br><span class="line">        &#125;</span><br><span class="line">        catch(CloneNotSupportedException e)</span><br><span class="line">        &#123;</span><br><span class="line">            System.out.println(&quot;拷贝正方形失败!&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        return b;</span><br><span class="line">    &#125;</span><br><span class="line">    public void countArea()</span><br><span class="line">    &#123;</span><br><span class="line">        int a&#x3D;0;</span><br><span class="line">        System.out.print(&quot;这是一个正方形，请输入它的边长：&quot;);</span><br><span class="line">        Scanner input&#x3D;new Scanner(System.in);</span><br><span class="line">        a&#x3D;input.nextInt();</span><br><span class="line">        System.out.println(&quot;该正方形的面积&#x3D;&quot;+a*a+&quot;\n&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">class ProtoTypeManager</span><br><span class="line">&#123;</span><br><span class="line">    private HashMap&lt;String, Shape&gt;ht&#x3D;new HashMap&lt;String,Shape&gt;(); </span><br><span class="line">    public ProtoTypeManager()</span><br><span class="line">    &#123;</span><br><span class="line">        ht.put(&quot;Circle&quot;,new Circle());</span><br><span class="line">           ht.put(&quot;Square&quot;,new Square());</span><br><span class="line">    &#125; </span><br><span class="line">    public void addshape(String key,Shape obj)</span><br><span class="line">    &#123;</span><br><span class="line">        ht.put(key,obj);</span><br><span class="line">    &#125;</span><br><span class="line">    public Shape getShape(String key)</span><br><span class="line">    &#123;</span><br><span class="line">        Shape temp&#x3D;ht.get(key);</span><br><span class="line">        return (Shape) temp.clone();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">public class ProtoTypeShape</span><br><span class="line">&#123;</span><br><span class="line">    public static void main(String[] args)</span><br><span class="line">    &#123;</span><br><span class="line">        ProtoTypeManager pm&#x3D;new ProtoTypeManager();    </span><br><span class="line">        Shape obj1&#x3D;(Circle)pm.getShape(&quot;Circle&quot;);</span><br><span class="line">        obj1.countArea();          </span><br><span class="line">        Shape obj2&#x3D;(Shape)pm.getShape(&quot;Square&quot;);</span><br><span class="line">        obj2.countArea();     </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">这是一个圆，请输入圆的半径：3</span><br><span class="line">该圆的面积&#x3D;28.2735</span><br><span class="line"></span><br><span class="line">这是一个正方形，请输入它的边长：3</span><br><span class="line">该正方形的面积&#x3D;9</span><br></pre></td></tr></table></figure>
    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9017%E3%80%91%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F%E6%A6%82%E8%BF%B0%EF%BC%88%E7%BB%93%E6%9E%84%E5%9E%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E5%88%86%E7%B1%BB%EF%BC%89/" rel="prev" title="【17】结构型模式概述（结构型模式的分类）">
      <i class="fa fa-chevron-left"></i> 【17】结构型模式概述（结构型模式的分类）
    </a></div>
      <div class="post-nav-item">
    <a href="/myblogs/2020/01/17/%E3%80%9012%E3%80%91%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%EF%BC%88%E5%8D%95%E4%BE%8B%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%EF%BC%89%E8%AF%A6%E8%A7%A3/" rel="next" title="【12】单例模式（单例设计模式）详解">
      【12】单例模式（单例设计模式）详解 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#【13】原型模式（原型设计模式）详解"><span class="nav-number">1.</span> <span class="nav-text">【13】原型模式（原型设计模式）详解</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型模式的定义与特点"><span class="nav-number">2.</span> <span class="nav-text">原型模式的定义与特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型模式的结构与实现"><span class="nav-number">3.</span> <span class="nav-text">原型模式的结构与实现</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-模式的结构"><span class="nav-number">3.1.</span> <span class="nav-text">1. 模式的结构</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-模式的实现"><span class="nav-number">3.2.</span> <span class="nav-text">2. 模式的实现</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型模式的应用实例"><span class="nav-number">4.</span> <span class="nav-text">原型模式的应用实例</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型模式的应用场景"><span class="nav-number">5.</span> <span class="nav-text">原型模式的应用场景</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原型模式的扩展"><span class="nav-number">6.</span> <span class="nav-text">原型模式的扩展</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="H.m"
      src="http://img.hao661.com/zt.hao661.com/uploads/allimg/141006/0644042451-0.jpg">
  <p class="site-author-name" itemprop="name">H.m</p>
  <div class="site-description" itemprop="description">欢迎您的到来！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/myblogs/archives/">
        
          <span class="site-state-item-count">42</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/myblogs/categories/">
          
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/hackmgod" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;hackmgod" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/hackmgod@foxmail.com" title="E-Mail → hackmgod@foxmail.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/975643993@qq.com" title="QQ → 975643993@qq.com"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/myblogs/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.baidu.com/" title="https:&#x2F;&#x2F;www.baidu.com&#x2F;" rel="noopener" target="_blank">百度</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.iqiyi.com/" title="https:&#x2F;&#x2F;www.iqiyi.com&#x2F;" rel="noopener" target="_blank">爱奇艺</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        <!-- 用下面的符号注释，注释代码用下面括号括起来 -->
<!-- -->

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">H.m</span>
</div>


<!--
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.0
  </div> -->

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="powered-by">
  <i class="fa fa-user-md"></i>
  <span id="busuanzi_container_site_pv">
    本站访问量:<span id="busuanzi_value_site_pv"></span>次
  </span>
  <span class="post-meta-divider">|</span>
  <span id="busuanzi_container_site_uv">
    本站总访客量：<span id="busuanzi_value_site_uv"></span>人
  </span>
</div>





        








      </div>
    </footer>
  </div>

  
  <script src="/myblogs/lib/anime.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.min.js"></script>
  <script src="/myblogs/lib/velocity/velocity.ui.min.js"></script>

<script src="/myblogs/js/utils.js"></script>

<script src="/myblogs/js/motion.js"></script>


<script src="/myblogs/js/schemes/pisces.js"></script>


<script src="/myblogs/js/next-boot.js"></script>




  




  
<script src="/myblogs/js/local-search.js"></script>













  

  

</body>
</html>


<a href="https://github.com/hackmgod" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>


<!-- 动态背景 -->
<script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>